package com.foreverwin.jzymes.framework.sapjco;

import com.sap.conn.jco.ext.Environment;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.ResourceUtils;

import javax.annotation.PostConstruct;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;

@Configuration
public class SapConnConfig {

    @Value("${mes.sap.configSuffix}")
    String configSuffix;

    @Value("${mes.sap.configLocations}")
    String configLocations;

    @PostConstruct
    public void registerDestinationDataProvider(){
        if( !Environment.isDestinationDataProviderRegistered() ){
            CustomDestinationDataProvider provider = new CustomDestinationDataProvider();
            try {
                File jcoDir = ResourceUtils.getFile( configLocations );
                File[] jcoFiles = jcoDir.listFiles();
                for( File f : jcoFiles ){
                    if( f.getName().endsWith( configSuffix ) ){
                        Properties properties = new Properties();
                        properties.load( new FileInputStream( f ) );
                        provider.addDestinationProperties( f.getName().substring( 0, f.getName().indexOf( configSuffix ) ), properties );
                    }
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            Environment.registerDestinationDataProvider( provider );
        }
    }
}
